package com.app.bimo.commonbusiness.util;/**
 * Dec:
 * Created by limo on 16/8/11.
 */

import android.text.InputFilter;
import android.text.Spanned;

/**
 * 描述：
 * 作者：limo on 16/8/11 17:10
 */
public class LengthFilter implements InputFilter {
    private final int ymax;
    private OutOfMaxHintListener listener;

    public LengthFilter(int max) {
        ymax = max;
    }

    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                               int dstart, int dend) {
        int keep = ymax - (dest.length() - (dend - dstart));
        if (keep <= 0) {
            listener.showHint();
            return "";
        } else if (keep >= end - start) {
            return null; // keep original
        } else {
            keep += start;
            if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                --keep;
                if (keep == start) {
                    return "";
                }
            }
            return source.subSequence(start, keep);
        }
    }

    /**
     * @return the maximum length enforced by this input filter
     */
    public int getMax() {
        return ymax;
    }

    public interface OutOfMaxHintListener{
        public void showHint();
    }

    public void setListener(OutOfMaxHintListener listener) {
        this.listener = listener;
    }
}
